package net.jiastudy.web;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import net.jiastudy.core.exception.ServiceException;

@ControllerAdvice(basePackages = "net.jiastudy.web.rest.controller")
public class JsonThrowableHandler {
	protected final Logger logger = LoggerFactory.getLogger(this.getClass());
	@ExceptionHandler(value = MethodArgumentNotValidException.class)
	@ResponseBody
	public JsonResponseWrapper<List<?>> jsonErrorHandler(HttpServletRequest req, MethodArgumentNotValidException e)
			throws Exception {
		JsonResponseWrapper<List<?>> err = new JsonResponseWrapper<List<?>>(e.getBindingResult().getAllErrors());
		err.setMessage("数据校验失败！");
		err.setStatus(String.valueOf(HttpServletResponse.SC_NOT_ACCEPTABLE));
		return err;
	}
	
	@ExceptionHandler(value = ServiceException.class)
	@ResponseBody
	public JsonResponseWrapper<String> jsonErrorHandler(HttpServletRequest req, ServiceException e) {
		JsonResponseWrapper<String> err = new JsonResponseWrapper<String>(e.getMessage());
		err.setMessage(e.getMessage());
		err.setStatus(e.getCode());
		return err;
	}
	
	@ExceptionHandler(value = AccessDeniedException.class)
	@ResponseBody
	public JsonResponseWrapper<String> accessDeniedExceptionHandler(HttpServletRequest req, AccessDeniedException e){
		JsonResponseWrapper<String> err = new JsonResponseWrapper<String>(e.getMessage());
		err.setMessage("不允许访问");
		err.setStatus(String.valueOf(HttpServletResponse.SC_FORBIDDEN));
		return err;
	}
	
	@ExceptionHandler(Throwable.class)
	@ResponseBody
	public JsonResponseWrapper<String> throwableHandler(HttpServletRequest req, Throwable e) throws Exception {
		JsonResponseWrapper<String> err = new JsonResponseWrapper<String>();
		err.setMessage("服务器繁忙");
		err.setStatus(String.valueOf(HttpServletResponse.SC_INTERNAL_SERVER_ERROR));
		logger.error("服务器异常：",e);
		return err;
	}
}
